package cn.chencq.moudle.sys.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.chencq.constants.Constants;
import cn.chencq.exception.MyException;
import cn.chencq.moudle.sys.dao.BaseDao;
import cn.chencq.moudle.sys.dao.SysRoleDao;
import cn.chencq.moudle.sys.entity.SysRole;
import cn.chencq.moudle.sys.service.SysRoleMenuService;
import cn.chencq.moudle.sys.service.SysRoleService;
import cn.chencq.moudle.sys.service.SysUserService;

@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole> implements SysRoleService {

	@Autowired
	private SysRoleDao sysRoleDao;

	@Autowired
	private SysRoleMenuService sysRoleMenuService;

	@Autowired
	private SysUserService sysUserService;

	@Override
	protected BaseDao getBaseDao() {
		return sysRoleDao;
	}

	@Override
	@Transactional
	public void save(SysRole role) {
		// 检查权限是否越权
		checkPrems(role);

		role.setCreateTime(new Date());
		sysRoleDao.save(role);

		// 保存角色与菜单关系
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
	}

	/**
	 * 检查权限是否越权
	 */
	private void checkPrems(SysRole role) {
		// 如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
		if (role.getCreateUserId() == Constants.SUPER_ADMIN) {
			return;
		}

		// 查询用户所拥有的菜单列表
		List<Long> menuIdList = sysUserService.queryAllMenuId(role.getCreateUserId());

		// 判断是否越权
		if (!menuIdList.containsAll(role.getMenuIdList())) {
			throw new MyException("新增角色的权限，已超出你的权限范围");
		}
	}

	@Override
	@Transactional
	public void updateRole(SysRole role) {
		// 检查权限是否越权
		checkPrems(role);

		sysRoleDao.updateByPrimaryKey(role);

		// 更新角色与菜单关系
		sysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
	}

	@Override
	public List<Long> queryRoleIdList(Long createUserId) {
		return sysRoleDao.queryRoleIdList(createUserId);
	}
}
